<template>
	<div class="w100">
		<el-upload action="" :accept="accept" multiple style="text-align: left;padding: 3px 10px;" :before-upload="beforeUpload" v-if="!readOnly">
			<vp-btn :loading="loading" type="primary" class="mr-20">
				<slot v-if="$slots.header" name="header"/>
				<div v-else>
					<vp-label zh="上传" en="Upload"/>
					<SvgIcon name="ele-Upload" class="el-icon--right"></SvgIcon>
				</div>
			</vp-btn>
		</el-upload>
		<div v-if="showAttachment" v-for="(attachment, index) in attachmentList" :key="index" class="upload-list-item">
			<div class="upload-list-item-info" @click="openBase64(attachment)">
				<a class="upload-list-item-name">
					<el-icon class="mr6" style="color: var(--el-text-color-secondary);"><ele-Document/></el-icon>
					<span class="upload-list-item-file-name">{{attachment.wbwjm + '.' + attachment.hzm}}</span>
					<el-progress type="circle" width="60" :percentage="attachment.progress"  v-if="attachment.showRow" />
				</a>
			</div>
			<!-- <el-icon class="upload-list-item-check" v-if="!readOnly">
				<i class="el-icon el-icon--upload-success el-icon--circle-check"><svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M512 896a384 384 0 1 0 0-768 384 384 0 0 0 0 768zm0 64a448 448 0 1 1 0-896 448 448 0 0 1 0 896z"></path><path fill="currentColor" d="M745.344 361.344a32 32 0 0 1 45.312 45.312l-288 288a32 32 0 0 1-45.312 0l-160-160a32 32 0 1 1 45.312-45.312L480 626.752l265.344-265.408z"></path></svg></i>
			</el-icon> -->
			<el-icon class="upload-list-item-close" @click="deleteFile(index)" v-if="!readOnly"><SvgIcon name="ele-Close"></SvgIcon></el-icon>
		</div>
	</div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';
import request from '/@/utils/request';
import axios from 'axios';
import { Session } from '/@/utils/storage';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

export default defineComponent({
	name: 'rowAttachment',
	emits: ['attachmentListEmit'],
	props: {
		attachmentList: Array,
		readOnly: Boolean,
		replaceOld:{	// 只保留一个附件，新附件会替换原附件
            type:Boolean,
            default:false
        },
		disableDownload: {
			type: Number,
			default:0
		},
		showAttachment: {
			type:Boolean,
            default:true
		},
		accept: {
			type:String,
            default:""
		}
	},
	setup(props, context) {
		const state = reactive({
			loading: false,
			value: '',
			visiable: true,
		});
		const deleteFile = (index: any) => {
			let attachmentList = props.attachmentList ? props.attachmentList : [];
			attachmentList.splice(index, 1);
			context.emit('attachmentListEmit', attachmentList);
		};
		// 上传文件之前的方法
		const beforeUpload = (file: any) => {
			if (file) {
				let submitData = new FormData();
				submitData.append('file', file);
				state.loading = true;
				request.post(`/file/upload`, submitData, { headers: { 'content-type': 'multipart/form-data' } }).then(res => {
					state.loading = false;
					if (res.data && res.data.length) {
						let attachmentList = props.attachmentList ? props.attachmentList : [];
						if (props.replaceOld) {
							attachmentList = [...res.data];
						} else {
							attachmentList = [...attachmentList, ...res.data];
						}
						context.emit('attachmentListEmit', attachmentList);
					}
				});
			}
			return false;
		};

		const router = useRouter()
		const openBase64 = (attachment: any) => {
			let viewType = '';
			if (attachment.hzm == 'PNG' || attachment.hzm == 'JPG' || attachment.hzm == 'BMP') {
			viewType="IMAGE"
			} else if (attachment.hzm == 'PDF') {
			viewType="PDF"
			} else if(attachment.hzm == "MP4"){
			viewType="VIDEO"
			} else if(attachment.hzm == "MP3"){
			viewType="AUDIO"
			}
			if(viewType !== ""){
				const {href} = router.resolve({
					name:"fileView",
					params: {
					id: attachment.id,
					type: viewType,
					disableDownload: props.disableDownload
					}
				})
				window.open(href, '_blank');
			}else{
				if (props.disableDownload === 1) {
					ElMessage.error("无权下载");
				} else {
					downloadAttachment(attachment);
				}
			}
		};


		const downloadAttachment = (attachment: any) => {
			if(attachment.showRow){
				return;
			}
			attachment.showRow = true;
			attachment.progress = 0;
			const instance = axios.create({
				baseURL: import.meta.env.VITE_API_URL as any, // url = base url + request url
				withCredentials: true, // send cookies when cross-domain requests
				// timeout: 3600000, // request timeout
				responseType: 'blob',
				headers: {
					'Content-type': 'application/json',
					token: `${Session.get('token')}`
				},onDownloadProgress: (progressEvent: any) =>{
					attachment.progress = ((progressEvent.loaded / progressEvent.total)* 100).toFixed(2);
					if (attachment.progress == 100) {
						attachment.showRow = false;
					}
				}
			});

			instance({
				method: 'get',
				url: `/file/download/${attachment.id}`
			})
				.then(res => {
					const content = res.data;
					const blob = new Blob([content]); //构造一个blob对象来处理数据
					const fileName = attachment.wbwjm + '.' + attachment.hzm;
					//对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
					//IE10以上支持blob但是依然不支持download
					if ('download' in document.createElement('a')) {
						//支持a标签download的浏览器
						const link = document.createElement('a'); //创建a标签
						link.download = fileName; //a标签添加属性
						link.style.display = 'none';
						link.href = URL.createObjectURL(blob);
						document.body.appendChild(link);
						link.click(); //执行下载
						URL.revokeObjectURL(link.href); //释放url
						document.body.removeChild(link); //释放标签
					} else {
						//其他浏览器
						navigator.msSaveBlob(blob, fileName);
					}
				})
				.catch(err => {
				});
		};

		return {
			...toRefs(state),
			...toRefs(props),
			beforeUpload,
			openBase64,
			deleteFile
		};
	}
});
</script>
<style scoped>
.upload-list-item {
	transition: all .5s cubic-bezier(.55,0,.1,1);
	position:relative;
	text-align: left;
	border-radius: 4px;
	padding: 1px 5px;
}
.upload-list-item:hover {
	background-color: var(--el-fill-color-dark);
}
.upload-list-item-info {
	display: inline-block;
	width: calc(100% - 30px);
    margin-left: 4px;
	color: var(--el-text-color-regular);
}
.upload-list-item-info:hover {
	color: var(--el-color-primary);
    cursor: pointer; 
}
.upload-list-item-name {
	display: inline-flex;
    align-items: center;
	width: 100%;
}
.upload-list-item-check {
	display: inline-flex;
	position: absolute;
	right: 5px;
	top: 0;
	color: var(--el-color-success);
	height: 100%;
    justify-content: center;
    align-items: center;
    transition: opacity var(--el-transition-duration);
}
.upload-list-item:hover .upload-list-item-check {
	display: none;
    opacity: 0;
}
.upload-list-item-close {
	display: none;
	position: absolute;
	right: 5px;
	top: 0;
	color: var(--el-text-color-regular);
	cursor: pointer;
	height: 100%;
    justify-content: center;
    align-items: center;
    transition: opacity var(--el-transition-duration);
}
.upload-list-item:hover .upload-list-item-close {
	display: inline-flex;
}
.upload-list-item-close:hover {
	opacity: 1;
    color: var(--el-color-primary);
}
.upload-list-item-file-name {
	overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
	text-decoration: underline;
}
:deep(.el-upload-list) {
    display: none;
}
</style>
